package com.star.spring.sharding.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.spring.sharding.entity.Account;
import com.star.spring.sharding.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    /**
     * 创建账户
     */
    @PostMapping("/create")
    public String createAccount(@RequestParam Long userId,
                                @RequestParam BigDecimal balance) {
        Account account = new Account(userId, balance);
        accountService.save(account);
        return "账户创建成功，账户ID: " + account.getAccountId();
    }

    /**
     * 根据账户ID查询账户
     */
    @GetMapping("/{accountId}")
    public Account getAccountById(@PathVariable Long accountId) {
        return accountService.getById(accountId);
    }

    /**
     * 根据用户ID查询账户
     */
    @GetMapping("/user/{userId}")
    public List<Account> getAccountsByUserId(@PathVariable Long userId) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return accountService.list(queryWrapper);
    }

    /**
     * 更新账户余额
     */
    @PutMapping("/{accountId}/balance")
    public String updateBalance(@PathVariable Long accountId,
                                @RequestParam BigDecimal balance) {
        Account account = accountService.getById(accountId);
        if (account != null) {
            account.setBalance(balance);
            accountService.updateById(account);
            return "账户余额更新成功";
        } else {
            return "账户不存在";
        }
    }

    /**
     * 删除账户
     */
    @DeleteMapping("/{accountId}")
    public String deleteAccount(@PathVariable Long accountId) {
        accountService.removeById(accountId);
        return "账户删除成功";
    }
}